#import "XLGPackFileUp.h"

#import "CGWService+ChannelProocol.h"

#import <CommonCrypto/CommonDigest.h>

@implementation XLGPackFileUp

- (XLGResult*)uploadFSChunksPackage:(XLGPackUpFileObj *)upfile fileData:(NSData *)data paras:(NSArray *)paras
{
    if (upfile.chunkTotal <= 0 || data.length <= 0)
        return [XLGResult result];
    
    XLGPackFileUpChannelProtocol *protocol = [XLGPackFileUpChannelProtocol new];
    EProtocolTransformType transformType = [protocol protocolTransformType];
    SEL sel;
    sel = @selector(sendChannelProtocol:);
    if(transformType == EProtocolTransformTypeSocketStream)
    {
        sel = @selector(longConnectSendChannelProtocol:);
    }
    else
    {
        sel = @selector(sendChannelProtocol:);
    }

    XLGResult *result ;
    
    XLGPackUpChunkObj *chunk = [[XLGPackUpChunkObj new] autorelease_mm];
    chunk.fileID = upfile.fileID;
    chunk.fileName = upfile.fileName;
    chunk.chunkNum = 1;//分包号从1开始
    chunk.chunkRange = @"";
    chunk.data = data;
    chunk.param = paras;
    
    if(self.isCanRequest == YES)
    {
        result = [self.service performSelector:sel withObject:^CProtocolBase *{
                        CProtocolBase *base = [protocol uploadFileChunksProtocol:chunk];
            
                        return base;
                  }];
    }
    else
    {
        result = [XLGResult resultWithOutResult:TERMINATEREADWRITE];
    }
    
    return result;
}

- (XLGResult*)uploadFileWithPath:(NSString*)filePath paras:(NSArray *)paras
{
    XLGResult *result = [XLGResult result];
    
    if ([filePath isHttpString] == NO)
    {
        if ([XMSFileHelper isFileDirExist:filePath] == YES)
        {
            NSData *data = [NSData dataWithContentsOfFile:filePath];
            
            XLGPackUpFileObj *fileObj = [[XLGPackUpFileObj new] autorelease_mm];
            fileObj.fileID = [XMSGUID GUIDString];
            fileObj.fileName = [NSString stringWithFormat:@"%@.%@", fileObj.fileID,[filePath pathExtension]];
            fileObj.chunkTotal = 1;//默认1个包
            
            result = [self uploadFSChunksPackage:fileObj fileData:data paras:paras];
        }
    }
    return result;
}

- (XLGResult*)uploadFileWithFileData:(NSData*)fileData fileName:(NSString*)fileName paras:(NSArray *)paras
{
    XLGResult *result = [XLGResult result];
    
    NSData *data = fileData;
    
    result = [self queryFSFiles:fileName fileData:data paras:paras];
    
    if (YES == result.outResult)
    {
        XLGPackUpFileObj *output = (XLGPackUpFileObj*)result.outObj;
        
        result = [self uploadFSChunksPackage:output fileData:data paras:nil];
    }
    else
        result = [XLGResult result];

    return result;
}

@end
